﻿using DigitalHealth.PACS.ChatWebSocket.Context;
using DigitalHealth.PACS.ChatWebSocket.Services;
using DigitalHealth.PACS.Model;
using System.Collections.Generic;
using System.Linq;

namespace DigitalHealth.PACS.ChatWebSocket.Repositories.Imp
{

    internal class ChatMessageRepository : IChatMessageRepository
    {
        public IChatUserRepository ChatUserRepository { get; set; }

        public ChatMessageRepository(IChatUserRepository chatUserRepository, ChatContext chatContext)
        {
            ChatUserRepository = chatUserRepository;
            ChatContext = chatContext;
        }

      

        public ChatContext ChatContext { get; set; }

        public void Create(ChatMessage chatMessage)
        {
            var senderUser=ChatContext.Users.Where(u => u.Id == chatMessage.SenderUser.Id).FirstOrDefault();
            var receiverUser=ChatContext.Users.Where(u => u.Id == chatMessage.ReceiverUser.Id).FirstOrDefault();
            if (senderUser==null||receiverUser==null)
            {
                return;
            }
            chatMessage.SenderUser = senderUser;
            chatMessage.ReceiverUser = receiverUser;
            ChatContext.ChatMessages.Add(chatMessage);
            ChatContext.SaveChanges();
        }

        public void Update(ChatMessage chatMessage)
        {
            ChatContext.ChatMessages.Update(chatMessage);
            ChatContext.SaveChanges();
        }

        public void Delete(ChatMessage chatMessage)
        {
            ChatContext.ChatMessages.Remove(chatMessage);
            ChatContext.SaveChanges();
        }

        public IEnumerable<ChatMessage> GetChatMessages()
        {
            return ChatContext.ChatMessages.ToList();
        }

        public ChatMessage GetChatMessageById(string id)
        {
            return ChatContext.ChatMessages.Find(id);
        }

        public IEnumerable<ChatMessage> GetChatMessagesByReceiverUser(User user)
        {
            return ChatContext.ChatMessages.Where(m => m.ReceiverUser == user);
        }

        public IEnumerable<ChatMessage> GetNotReadChatMessagesByReceiverUser(User user)
        {
            var result=ChatContext.ChatMessages.Where(m => m.ReceiverUser == user && m.State == Model.Enumeration.MsgState.未读&&m.SenderUser!=user).ToList();
            
            return result;
        }

        public bool ChatMessageExists(string id)
        {
            return ChatContext.ChatMessages.Any(m =>m.Id.ToString()==id);
        }
    }
}
